<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" width="800px" append-to-body @close="cancel">
    <!-- 修改待审核提示 -->
    <el-alert
      v-if="form.auditStatus === '修改待审核' && form.hasPendingChanges === 1"
      title="当前有修改正在审核中"
      type="warning"
      :closable="false"
      show-icon
      style="margin-bottom: 15px;"
    >
      <template slot="default">
        <div>您提交的修改正在等待管理员审核，学生端暂时看到的是原内容。</div>
        <div style="margin-top: 5px;">审核通过后，修改的内容将对学生可见。</div>
      </template>
    </el-alert>

    <!-- 已通过题目编辑提示 -->
    <el-alert
      v-if="form.topicId && form.auditStatus === '已通过' && (form.hasPendingChanges === null || form.hasPendingChanges === 0)"
      title="提示：修改已通过审核的题目需要重新审核"
      type="info"
      :closable="false"
      show-icon
      style="margin-bottom: 15px;"
    >
      <div>您正在修改已通过审核的题目，提交后需要等待管理员审核通过才能生效。</div>
    </el-alert>

    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="题目名称" prop="title">
            <el-input v-model="form.title" placeholder="请输入题目名称" maxlength="200" show-word-limit />
            <!-- 显示待审核的题目名称 -->
            <div v-if="form.pendingTitle" style="margin-top: 8px; padding: 8px; background-color: #FFF7E6; border-left: 3px solid #E6A23C; font-size: 12px;">
              <span style="color: #E6A23C; font-weight: bold;">待审核内容：</span>
              <span style="color: #606266;">{{ form.pendingTitle }}</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="难度等级" prop="difficulty">
            <el-select v-model="form.difficulty" placeholder="请选择难度等级" style="width: 100%">
              <el-option label="简单" value="简单" />
              <el-option label="中等" value="中等" />
              <el-option label="困难" value="困难" />
            </el-select>
            <!-- 显示待审核的难度 -->
            <div v-if="form.pendingDifficulty" style="margin-top: 8px; font-size: 12px; color: #E6A23C;">
              待审核：<el-tag :type="getPendingDifficultyType(form.pendingDifficulty)" size="mini">{{ form.pendingDifficulty }}</el-tag>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最大学生数" prop="maxStudents">
            <el-input-number v-model="form.maxStudents" :min="1" :max="10" style="width: 100%" />
            <!-- 显示待审核的最大学生数 -->
            <div v-if="form.pendingMaxStudents" style="margin-top: 8px; font-size: 12px; color: #E6A23C;">
              待审核：{{ form.pendingMaxStudents }}
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="技术标签" prop="tags">
            <!-- 已添加的标签 -->
            <div class="tags-container">
              <el-tag
                v-for="tag in form.tagsArray"
                :key="tag"
                closable
                :disable-transitions="false"
                @close="handleTagClose(tag)"
                style="margin-right: 10px; margin-bottom: 10px;"
              >
                {{ tag }}
              </el-tag>
              <!-- 输入框 -->
              <el-input
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                class="input-new-tag"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
                placeholder="输入标签后按回车"
              />
              <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加标签</el-button>
            </div>
            <div class="tag-tips">
              <span style="color: #909399; font-size: 12px;">
                常用标签：
                <el-link 
                  v-for="commonTag in commonTags" 
                  :key="commonTag"
                  type="primary" 
                  :underline="false" 
                  @click="addCommonTag(commonTag)"
                  style="margin-right: 8px; font-size: 12px;"
                >
                  {{ commonTag }}
                </el-link>
              </span>
            </div>
            <!-- 显示待审核的标签 -->
            <div v-if="form.pendingTags" style="margin-top: 8px; padding: 8px; background-color: #FFF7E6; border-left: 3px solid #E6A23C;">
              <span style="color: #E6A23C; font-size: 12px; font-weight: bold;">待审核标签：</span>
              <el-tag 
                v-for="tag in getPendingTagsArray()" 
                :key="tag" 
                size="small" 
                type="warning"
                style="margin-right: 8px; margin-top: 4px;"
              >{{ tag }}</el-tag>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="题目描述" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="4"
              placeholder="请输入题目描述"
              maxlength="2000"
              show-word-limit
            />
            <!-- 显示待审核的描述 -->
            <div v-if="form.pendingDescription" style="margin-top: 8px; padding: 8px; background-color: #FFF7E6; border-left: 3px solid #E6A23C;">
              <div style="color: #E6A23C; font-size: 12px; font-weight: bold; margin-bottom: 4px;">待审核内容：</div>
              <div style="color: #606266; font-size: 12px; white-space: pre-wrap;">{{ form.pendingDescription }}</div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="技能要求" prop="requirements">
            <el-input
              v-model="form.requirements"
              type="textarea"
              :rows="4"
              placeholder="请输入技能要求"
              maxlength="2000"
              show-word-limit
            />
            <!-- 显示待审核的技能要求 -->
            <div v-if="form.pendingRequirements" style="margin-top: 8px; padding: 8px; background-color: #FFF7E6; border-left: 3px solid #E6A23C;">
              <div style="color: #E6A23C; font-size: 12px; font-weight: bold; margin-bottom: 4px;">待审核内容：</div>
              <div style="color: #606266; font-size: 12px; white-space: pre-wrap;">{{ form.pendingRequirements }}</div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getTeacherTopic, addTopic, updateTopic } from "@/api/system/topic";

export default {
  name: "TopicForm",
  data() {
    return {
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单参数
      form: {},
      // 标签输入相关
      inputVisible: false,
      inputValue: '',
      // 常用技术标签（点击快速添加）
      commonTags: [
        "Java", "Python", "JavaScript", "Vue", "React", "Angular",
        "Spring Boot", "MyBatis", "MySQL", "Oracle", "Redis",
        "HTML", "CSS", "Node.js", "Express", "Django",
        "机器学习", "深度学习", "人工智能", "大数据", "云计算"
      ],
      // 表单校验
      rules: {
        title: [
          { required: true, message: "题目名称不能为空", trigger: "blur" }
        ],
        difficulty: [
          { required: true, message: "请选择难度等级", trigger: "change" }
        ],
        maxStudents: [
          { required: true, message: "最大学生数不能为空", trigger: "blur" }
        ],
        description: [
          { required: true, message: "题目描述不能为空", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    /** 打开对话框 */
    openDialog(topicId) {
      this.reset();
      if (topicId) {
        this.title = "修改题目";
        getTeacherTopic(topicId).then(response => {
          this.form = response.data;
          // 解析tags JSON字符串为数组
          if (this.form.tags) {
            try {
              this.form.tagsArray = JSON.parse(this.form.tags);
            } catch (e) {
              this.form.tagsArray = [];
            }
          }
          this.dialogVisible = true;
        });
      } else {
        this.title = "新增题目";
        this.dialogVisible = true;
      }
    },
    
    /** 获取待审核标签数组 */
    getPendingTagsArray() {
      if (!this.form.pendingTags) return [];
      try {
        return JSON.parse(this.form.pendingTags);
      } catch (e) {
        return [];
      }
    },

    /** 获取待审核难度的标签类型 */
    getPendingDifficultyType(difficulty) {
      const map = {
        '简单': 'success',
        '中等': '',
        '困难': 'danger'
      };
      return map[difficulty] || 'info';
    },
    
    /** 显示输入框 */
    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    
    /** 确认输入标签 */
    handleInputConfirm() {
      let inputValue = this.inputValue.trim();
      if (inputValue) {
        // 检查是否已存在
        if (this.form.tagsArray.indexOf(inputValue) === -1) {
          this.form.tagsArray.push(inputValue);
        } else {
          this.$message.warning('该标签已存在');
        }
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    
    /** 删除标签 */
    handleTagClose(tag) {
      this.form.tagsArray.splice(this.form.tagsArray.indexOf(tag), 1);
    },
    
    /** 添加常用标签 */
    addCommonTag(tag) {
      if (this.form.tagsArray.indexOf(tag) === -1) {
        this.form.tagsArray.push(tag);
        this.$message.success('标签已添加');
      } else {
        this.$message.warning('该标签已存在');
      }
    },
    
    // 表单重置
    reset() {
      this.form = {
        topicId: null,
        title: null,
        description: null,
        requirements: null,
        difficulty: "中等",
        maxStudents: 1,
        tags: null,
        tagsArray: [],
        remark: null,
        auditStatus: null,
        hasPendingChanges: null,
        pendingTitle: null,
        pendingDescription: null,
        pendingRequirements: null,
        pendingDifficulty: null,
        pendingMaxStudents: null,
        pendingTags: null
      };
      this.inputVisible = false;
      this.inputValue = '';
      this.resetForm("form");
    },
    
    /** 取消按钮 */
    cancel() {
      this.dialogVisible = false;
      this.reset();
    },
    
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 将标签数组转换为JSON字符串
          if (this.form.tagsArray && this.form.tagsArray.length > 0) {
            this.form.tags = JSON.stringify(this.form.tagsArray);
          } else {
            this.form.tags = null;
          }

          if (this.form.topicId != null) {
            // 修改题目
            updateTopic(this.form).then(response => {
              // 后端会返回特殊的提示信息
              if (response.msg) {
                this.$modal.msgSuccess(response.msg);
              } else {
                this.$modal.msgSuccess("修改成功");
              }
              this.dialogVisible = false;
              this.$emit("success");
            }).catch(error => {
              // 如果有错误信息，显示
              if (error.response && error.response.data && error.response.data.msg) {
                this.$modal.msgError(error.response.data.msg);
              }
            });
          } else {
            // 新增题目
            addTopic(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dialogVisible = false;
              this.$emit("success");
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.tags-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 10px;
}

.input-new-tag {
  width: 150px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
  margin-bottom: 10px;
}

.tag-tips {
  padding: 10px;
  background-color: #f4f4f5;
  border-radius: 4px;
}
</style>